package com.example.socialmediaplatform.controller;

import com.example.socialmediaplatform.model.Profile;
import com.example.socialmediaplatform.model.ProfileDTO;
import com.example.socialmediaplatform.model.ProfileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user/profile")
public class UserProfileController {
    @Autowired
    private ProfileRepository profileRepository;

    // 查询当前用户资料
    @GetMapping("")
    public ResponseEntity<?> getProfile(Authentication authentication) {
        if (authentication == null) {
            return ResponseEntity.status(401).body("未认证或token无效");
        }
        String username = authentication.getName();
        Profile profile = profileRepository.findByUsername(username);
        if (profile == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(profile);
    }

    // 编辑当前用户资料
    @PutMapping("")
    public ResponseEntity<?> updateProfile(Authentication authentication, @RequestBody ProfileDTO profileDTO) {
        String username = authentication.getName();
        Profile profile = profileRepository.findByUsername(username);
        if (profile == null) {
            return ResponseEntity.notFound().build();
        }
        // 只允许修改部分字段
        profile.setFirstname(profileDTO.getFirstname());
        profile.setLastname(profileDTO.getLastname());
        profile.setAboutme(profileDTO.getAboutme());
        profile.setPhonenumber(profileDTO.getPhonenumber());
        profile.setStudentnumber(profileDTO.getStudentnumber());
        profileRepository.save(profile);
        return ResponseEntity.ok(profile);
    }
} 
